from logger import log
import psycopg2
from psycopg2 import extras

class PostgreSQL:
	def __init__(self):
		pass

	def connect(self, host, user, password, database):
		self.cursor = None
		self.returnAsDict = False
		try:
			self.conn = psycopg2.connect(database=database, host=host, user=user, password=password)
		except:
			raise Exception('Failed to connect to %s'%host)
#			log('Failed to connect to %s'%host)
#			return False
		log('Connected to SQL server')

	def setDict(self, returnAsDict):
		self.returnAsDict = returnAsDict

	def execute(self, query, params = []):
		if self.returnAsDict:
			self.cursor = self.conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
		else:
			self.cursor = self.conn.cursor()
		self.cursor.execute(query.strip(), params)
		log('Executed query `%s`'%self.cursor.query)
		pass

	def loadList(self, query = None, params = []):
		if query:
			self.execute(query, params)
		return self.cursor.fetchall()
		pass

	def loadRows(self, query = None, params = []):
		return self.loadList(query, params)

	def loadRow(self, query = None, params = []):
		if query:
			self.execute(query, params)
		return self.cursor.fetchone()
		pass

	def loadValue(self, query = None, params = []):
		if query:
			self.execute(query, params);
		return self.cursor.fetchone()[0]
